package com.better.frontend.service.scoreSelection;

import com.alibaba.fastjson.JSONObject;
import com.better.backend.dataComputingService.model.scoreSelection.ScoreSelection;
import com.better.backend.dataComputingService.model.scoreSelection.ScoreSelectionDetail;
import com.better.backend.dataComputingService.repository.scoreSelection.ScoreSelectionRespository;
import com.better.backend.mqReceiverService.calType.calService.CalService;
import com.better.backend.mqReceiverService.examReceiver.model.ExamModel;
import com.better.backend.mqReceiverService.examReceiver.model.ExamUnitModel;
import com.better.backend.mqReceiverService.examReceiver.model.SubjectScoreModel;
import com.better.backend.mqReceiverService.examReceiver.repository.ExamRepsitory;
import com.better.common.base.ServiceResponse;
import com.better.common.exception.DescribeException;
import com.better.common.jwtauth.secruity.JWTUserDetails;
import com.better.common.utils.GlobalUtil;
import com.better.common.utils.ServiceResponseHandle;
import com.better.common.utils.SessionUtils;
import com.better.consist.CalTypeEnum;
import com.better.consist.GlobalTypeEnum;
import com.better.frontend.Iservice.exam.ExamService;
import com.better.frontend.Iservice.scoreSelection.ScoreSelectionService;
import com.better.frontend.vo.scoresegment.ScoreSelectionVo;
import com.better.frontend.vo.scoresegment.ScoreVo;
import com.better.frontend.vo.studentScore.SubjectList;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 设置分数段
 * @author tangping
 */
@Service
public class ScoreSelectionServiceImpl implements ScoreSelectionService {
    @Resource
    private ScoreSelectionRespository scoreSelectionRespository;
    @Resource
    private ExamService examService;
    @Resource
    private CalService calService;
    @Resource
    private ExamRepsitory examRepsitory;


    private final Logger logger = LoggerFactory.getLogger(ScoreSelectionServiceImpl.class);
    @Override
    public ServiceResponse addScoreSelection(ScoreSelection scoreSelection) {
        if(scoreSelection == null){
            return ServiceResponseHandle.failed("参数传递错误");
        }
        JWTUserDetails user = SessionUtils.getUserInfo();
        scoreSelection.setSchoolId(user.getSchoolId());
        scoreSelection.setSchoolName(user.getSchoolName());
        if(StringUtils.isEmpty(scoreSelection.getId())){
            scoreSelection.setId(GlobalUtil.createGlobalId());
        }
        List<ScoreSelectionDetail> scoreSelectionDetailList = scoreSelection.getScoreSelectionDetailList();
        scoreSelectionDetailList.forEach(scoreSelectionDetail -> {
            scoreSelectionDetail.setSubjectId(scoreSelection.getSubjectId());
            if("0".equals(scoreSelectionDetail.getSubjectId())){
                scoreSelectionDetail.setType(GlobalTypeEnum.ALL.getCode());
            }else{
                scoreSelectionDetail.setType(GlobalTypeEnum.SUBJECT.getCode());
            }
            String name = scoreSelectionDetail.getSelectName()+"优踩线生";
            scoreSelectionDetail.setSelectValue(GlobalTypeEnum.getCodeByName(scoreSelectionDetail.getSelectName()));
            scoreSelectionDetail.setFootScoreName(name);
            scoreSelectionDetail.setFootScoreValue(GlobalTypeEnum.getCodeByName(name));
            scoreSelectionDetail.setId(GlobalUtil.createGlobalId());
        });
        ScoreSelectionDetail scoreSelectionDetail = scoreSelectionDetailList.stream().sorted((e1, e2) -> e2.getSelectValue().compareTo(e1.getSelectValue())).collect(Collectors.toList()).get(0);
        boolean flag = !GlobalTypeEnum.SELECT_F.getCode().equals(scoreSelectionDetail.getSelectValue()) && scoreSelectionDetail.getStandardScore()!=0d;
        if(scoreSelectionDetail !=null && flag){
            Integer selectValue = scoreSelectionDetail.getSelectValue()+1;
            Integer footValue = scoreSelectionDetail.getFootScoreValue()+1;
            ScoreSelectionDetail scoreSelectionDetail1 = new ScoreSelectionDetail();
            scoreSelectionDetail1.setId(GlobalUtil.createGlobalId());
            scoreSelectionDetail1.setSelectValue(selectValue);
            scoreSelectionDetail1.setSelectName(GlobalTypeEnum.getName(selectValue));
            scoreSelectionDetail1.setFootScoreValue(footValue);
            scoreSelectionDetail1.setFootScoreName(GlobalTypeEnum.getName(footValue));
            scoreSelectionDetail1.setStartScore(0d);
            scoreSelectionDetail1.setEndScore(scoreSelectionDetail.getStartScore());
            scoreSelectionDetail1.setCheck(true);
            scoreSelectionDetail1.setSubjectId(scoreSelectionDetail.getSubjectId());
            scoreSelectionDetail1.setStandardScore(0d);
            scoreSelectionDetail1.setUpScore(1d);
            scoreSelectionDetail1.setDownScore(0d);
            scoreSelectionDetailList.add(scoreSelectionDetail1);
        }
        scoreSelection.setScoreSelectionDetailList(scoreSelectionDetailList);
        logger.info("保存参数名称:"+ JSONObject.toJSONString(scoreSelection));
        this.scoreSelectionRespository.save(scoreSelection);
        //计算分数段和踩线生
       // this.calService.calScoreSelection(scoreSelection.getExamId(),scoreSelection.getGradeId());
        return ServiceResponseHandle.success("");
    }

    /**
     *  获取标准
     * @return
     */
    @Override
    public ServiceResponse getAllSelection(String gradeId,String examId) {
        List<SubjectScoreModel> subjectScoreModels =  this.examService.findSubByExamIDAndGraID(examId, gradeId);
        int totalScore = subjectScoreModels.stream().mapToInt(e->Integer.parseInt(e.getToalscore())).sum();
        SubjectScoreModel subjectScoreModel = new SubjectScoreModel();
        subjectScoreModel.setSubjectname("总分");
        subjectScoreModel.setToalscore(totalScore+"");
        subjectScoreModel.setSubjectid("0");
        subjectScoreModels.add(subjectScoreModel);
        return ServiceResponseHandle.success(subjectScoreModels);


    }

    /**
     *  获取到分数段信息
     * @param subjectId
     * @param examId
     * @return
     */
    @Override
    public ServiceResponse getSelectionByCondition(String subjectId, String examId,String gradeId) {
        List<ScoreSelection> scoreSelectionList = this.scoreSelectionRespository.findByExamIdAndGradeId(examId,gradeId);
        if(CollectionUtils.isNotEmpty(scoreSelectionList)){
            ScoreSelection scoreSelection = getScoreSelection(subjectId,scoreSelectionList);
            if(scoreSelection ==null){
                return ServiceResponseHandle.success(null);
            }
            ScoreSelectionVo scoreSelectionVo = new ScoreSelectionVo();
            scoreSelectionVo.setExamId(scoreSelection.getExamId());
            scoreSelectionVo.setExamName(scoreSelection.getExamName());
            scoreSelectionVo.setId(scoreSelection.getId());
            if(scoreSelection !=null){
                List<ScoreVo> scoreVoList = new ArrayList<>();
                scoreSelection.getScoreSelectionDetailList().forEach(e->{
                    ScoreVo scoreVo = new ScoreVo();
                    scoreVo.setCheck(e.isCheck());
                    scoreVo.setDownScore(e.getDownScore()+"");
                    scoreVo.setUpScore(e.getUpScore()+"");
                    scoreVo.setStandardScore(e.getStandardScore()+"");
                    scoreVo.setSelectName(e.getSelectName());
                    scoreVo.setSubjectId(e.getSubjectId());
                    scoreVo.setStartScore(e.getStartScore()+"");
                    scoreVo.setEndScore(e.getEndScore()+"");
                    scoreVoList.add(scoreVo);
                });
                scoreSelectionVo.setScoreVoList(scoreVoList);
            }
            return ServiceResponseHandle.success(scoreSelectionVo);
        }else{
            return ServiceResponseHandle.success(null);
        }

    }

    /**
     *  根据考试id获得对应的科目信息以及分数
     * @param examId
     * @return
     */
    @Override
    public ServiceResponse listSubjectList(String examId) {
        ExamModel examModel = this.examRepsitory.findOne(examId);
        //判断考试类型
        List<Map<String,Object>> gradeList = new ArrayList<>();
        if (CalTypeEnum.examtype_class.equals(examModel.getExamType())) {
            Set<String> collect = this.getCollect(examId, examModel.getGradeId());
            //获得对应的年级信息
            Map<String,Object> grade = new HashMap<>();
            grade.put("gradeId",examModel.getGradeId());
            grade.put("gradeName",examModel.getGradeName());
            //获取科目信息
            ExamUnitModel uM = examModel.getExamUnitModels().get(0);
            List<SubjectList> subjectList = new ArrayList<>();
            List<SubjectScoreModel> subjectScoreModels = uM.getSubjectScoreModels();
            if (CollectionUtils.isEmpty(subjectScoreModels)) {
                throw new DescribeException("-1000", "导入班级考试，查询参考科目分数信息异常！");
            }
            // 添加总分
            int totalScore = subjectScoreModels.stream().mapToInt(e -> Integer.parseInt(e.getToalscore())).sum();
            SubjectList s = new SubjectList();
            s.setSubjectId("0");
            s.setSubjectName("总分");
            s.setScore(totalScore+"");
            if(collect.contains("0")){
                s.setIsImport("2");
            }else{
                s.setIsImport("1");
            }
            subjectList.add(s);
            for (SubjectScoreModel sub : subjectScoreModels) {
                SubjectList sj = new SubjectList();
                sj.setSubjectId(sub.getSubjectid());
                sj.setSubjectName(sub.getSubjectname());
                sj.setScore(sub.getToalscore());
                if(collect.contains(sub.getSubjectid())){
                    sj.setIsImport("2");
                }else{
                    sj.setIsImport("1");
                }
                subjectList.add(sj);
            }
            grade.put("subjectList",subjectList);
            gradeList.add(grade);
        }else{
            List<ExamUnitModel> listUn = examModel.getExamUnitModels();
            for (ExamUnitModel u : listUn) {
                Map<String,Object> grade = new HashMap<>();
                Set<String> collect = this.getCollect(examId, u.getUnitId());
                grade.put("gradeId",u.getUnitId());
                grade.put("gradeName",u.getUnitName());
                List<SubjectList> subjectList = new ArrayList<>();
                List<SubjectScoreModel> subjectScoreModels = u.getSubjectScoreModels();
                if (CollectionUtils.isEmpty(subjectScoreModels)) {
                    throw new DescribeException("-1000", "导入校级考试，查询参考科目分数信息异常！");
                }
                int totalScore = subjectScoreModels.stream().mapToInt(e -> Integer.parseInt(e.getToalscore())).sum();
                SubjectList s = new SubjectList();
                s.setSubjectId("0");
                s.setSubjectName("总分");
                s.setScore(totalScore+"");
                if(collect.contains("0")){
                    s.setIsImport("2");
                }else{
                    s.setIsImport("1");
                }
                subjectList.add(s);
                for (SubjectScoreModel sub : subjectScoreModels) {
                    SubjectList sj = new SubjectList();
                    sj.setSubjectId(sub.getSubjectid());
                    sj.setSubjectName(sub.getSubjectname());
                    sj.setScore(sub.getToalscore());
                    if(collect.contains(sub.getSubjectid())){
                        sj.setIsImport("2");
                    }else{
                        sj.setIsImport("1");
                    }
                    subjectList.add(sj);
                }
                grade.put("subjectList",subjectList);
                gradeList.add(grade);
            }

        }
        return ServiceResponseHandle.success(gradeList);
    }

    public Set<String> getCollect(String examId,String gradeId){

        List<ScoreSelection> scoreSelections = new ArrayList<>();
        if(StringUtils.isEmpty(gradeId)){
            scoreSelections =  scoreSelectionRespository.findByExamId(examId);
        }else{
            scoreSelections =  scoreSelectionRespository.findByExamIdAndGradeId(examId, gradeId);
        }
        Set<String> collect = new HashSet<>();
        if(CollectionUtils.isNotEmpty(scoreSelections)){
            List<ScoreSelectionDetail> scoreSelectionDetailList = new ArrayList<>();
            scoreSelections.forEach(e->scoreSelectionDetailList.addAll(e.getScoreSelectionDetailList()));
            List<String> subjectIds = new ArrayList<>();
            scoreSelectionDetailList.forEach(e->subjectIds.add(e.getSubjectId()));
            collect = subjectIds.stream().collect(Collectors.toSet());
        }
        return collect;
    }

    private ScoreSelection getScoreSelection(String subjectId,List<ScoreSelection> scoreSelectionList){
        for (ScoreSelection scoreSelection : scoreSelectionList) {
            List<ScoreSelectionDetail> scoreSelectionDetailList = scoreSelection.getScoreSelectionDetailList();
            for (ScoreSelectionDetail scoreSelectionDetail : scoreSelectionDetailList) {
                if(subjectId.equals(scoreSelectionDetail.getSubjectId())){
                    return scoreSelection;
                }
            }
        }
        return null;
    }
}
